<template>
  <MyDrawer ref="MyDrawerRef" title="按钮操作" @submit="submit" :disabled="false" width="30%">
    <el-form :model="drawerProps.rowData" label-width="120" :rules="rules" ref="FormRef">
      <el-form-item label="按钮名称" prop="btnName">
        <el-input v-model="drawerProps.rowData.btnName"></el-input>
      </el-form-item>
      <el-form-item label="按钮标识" prop="btnTag">
        <el-input v-model="drawerProps.rowData.btnTag" :disabled="drawerProps.type === 'edit'"></el-input>
      </el-form-item>
      <el-form-item label="排序">
        <el-input-number v-model="drawerProps.rowData.sort" :min="1" :max="200"></el-input-number>
      </el-form-item>
      <el-form-item label="按钮分组" prop="btnGroup">
        <el-input v-model="drawerProps.rowData.btnGroup"></el-input>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="drawerProps.rowData.remark" type="textarea"></el-input>
      </el-form-item>
    </el-form>
  </MyDrawer>
</template>

<script setup lang="ts">
import { Btn } from "@/api/interface/btns";
import { AddBtn, EditBtn } from "@/api/modules/routes";
import MyDrawer from "@/components/MyDrawer/index.vue";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { reactive, ref } from "vue";

const MyDrawerRef = ref<InstanceType<typeof MyDrawer> | null>();

// -----------接受参数
interface DrawerProps {
  type: "add" | "edit";
  rowData: Btn.Option;
  api?: () => Promise<any>;
}

const initData: Btn.Option = {
  btnName: "",
  btnGroup: "",
  btnTag: "",
  remark: "",
  sort: 100
};

const drawerProps = ref<DrawerProps>({
  type: "add",
  rowData: JSON.parse(JSON.stringify(initData))
});

// -------------规则
const rules = reactive<FormRules>({
  btnName: [
    { required: true, message: "按钮必须的" },
    { min: 1, max: 40, message: "字符必须为1-20之间" }
  ],
  btnTag: [
    { required: true, message: "标识必须" },
    { min: 1, max: 40, message: "标识字符必须为1-20之间" }
  ],
  btnGroup: [
    { min: 0, max: 20, message: "字符不可超过20" },
    { required: true, message: "分组是必须的" }
  ],
  remark: [{ min: 0, max: 300, message: "不可超过300字" }]
});

const acceptParams = (params: any) => {
  if (params.rowData) {
    drawerProps.value = params;
  } else {
    drawerProps.value = params;
    drawerProps.value.rowData = JSON.parse(JSON.stringify(initData));
  }
  MyDrawerRef.value?.acceptParams();
};

// ----------------表单
const FormRef = ref<FormInstance>();
const submit = () => {
  FormRef.value?.validate(async valid => {
    if (valid) {
      try {
        if (drawerProps.value.type === "add") {
          await AddBtn(drawerProps.value.rowData);
          ElMessage.success("添加按钮成功");
        } else {
          await EditBtn(drawerProps.value.rowData);
          ElMessage.success("修改按钮成功");
        }
        await drawerProps.value.api!();
        MyDrawerRef.value?.close();
      } catch (error) {}
    }
  });
};

defineExpose({
  acceptParams
});
</script>

<style></style>
